<?php
class Adminform_model extends Base_Model
{
    const LISTTABLE = 'form_list_config';
    const FORMTABLE = 'form_config';
    const ITEMTABLE = 'form_items_config';
    private $_resource_url;
    private $_media_url;

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->helper('url');
        $this->_resource_url = $this->config->item('resource_url');
        $this->_media_url = $this->config->item('media_url');
    }

    public function checkExist($table,$pkey,$where)
    {
        return $this->db->select($pkey)->from($table)->where($where)->get()->row_array();
    }

    public function getData($formtable,$select='*',$where=array(),$offset = 0,$limit = 0,$sortkey = '',$sorttype = 'ASC')
    {
        $this->db->select($select)->from($formtable);
        if (!empty($where)) $this->db->where($where);
        if (!empty($limit)) $this->db->limit($limit,$offset);
        if (!empty($sortkey)) $this->db->order_by($sortkey,$sorttype);
        return $this->db->get()->result_array();

    }

    public function getRowData($formtable,$select='*',$where=array())
    {
        $this->db->select($select)->from($formtable);
        if (!empty($where)) $this->db->where($where);
        $this->db->limit(1);
        return $this->db->get()->row_array();

    }

    public function insertData($formtable,$data)
    {
        $this->db->insert($formtable,$data);
        return $this->db->insert_id();
    }

    public function updateData($formtable,$data,$where){
        $this->db->update($formtable,$data,$where);
    }

    public function deleteData($formtable,$where)
    {
        $this->db->delete($formtable,$where);
    }

    public function getList($formtype,$formtable,$where,$offset,$limit,$actionlist,$controller,$pkey,
                            $externalid = 0,$sortkey = '',$sorttype = '')
    {
        //获取form_list中规定要列表项目
        $res = $this->db->select()->from(self::LISTTABLE)
            ->where('name',$formtype)->order_by('sort','ASC')
            ->get()->result_array();

        $headers = array();//表头
        $keys = array();//list项目
        $types = array(); //list项目的类型
        foreach ($res as $row){
            $headers[] = $row['cname'];
            $keys[] = $row['ckey'];
            $types[$row['ckey']] = $row['type'];
        }

        $headers = array_merge($headers,array('操作'));
        //获取目标表格列表项目数据
        $keystr = '';
        if (!in_array($pkey,$keys)) $keys = array_merge(array($pkey),$keys);
        foreach ($keys as $k){
            $keystr .= $k.',';
        }
        $keystr = rtrim($keystr,',');
        $res = $this->getData($formtable,$keystr,$where,$offset,$limit,$sortkey,$sorttype);
        $resformat = array();
        foreach($res as $row){
            $rowformat = array();
            //列表项目数据重构
            foreach($row as $k => $v){
                if (isset($types[$k])){
                    switch ($types[$k]){
                        case 'image':
                            if (!empty($v)){
                                $v = preg_match("/http:\/\//i",$v)>0?$v:$this->_resource_url.$v;
                                $rowformat[$k]='<img src="'.$v.'" style="height:30px;">';
                            }else{$rowformat[$k]='';}
                            break;
                        case 'timestamp':
                            $rowformat[$k]=date('Y-m-d H:i:s',$v);
                            break;
                        case 'text_eplli':
                            $rowformat[$k]='<div class="txttoggle-wrap flex-column flex-align-center flex-justify-around flex-nowrap">'.
                                '<div class="txttoggle-content paragraph-cut">'.$v.'</div>'.
                                '<div class="txttoggle-icon"></div></div>';
                            break;
                        default:
                            $rowformat[$k]=$v;
                    }
                }
            }
            //列表项目操作按钮
            $rowformat['actionlist'] = $this->getActionList($actionlist,$controller,$row[$pkey],$externalid);
            $resformat[] = $rowformat;
        }

        return array('headers'=>$headers,'list'=>$resformat);

    }

    public function getActionList($actionlist,$controller,$pkeyval,$externalid)
    {
        $res = '';
        foreach ($actionlist as $action){
            switch ($action){
                case 'EDIT':
                    $param = empty($externalid)?'':'/'.$externalid;
                    $res .= '<a class="eidt-btn action-btn" href="'.site_url($controller).'update/'.$pkeyval.$param.'">修改</a>';
                    break;
                case 'DEL':
                    $param = empty($externalid)?'':'/'.$externalid;
                    $res .= '<a class="delete-btn action-btn" href="'.site_url($controller).'delete/'.$pkeyval.$param.'">删除</a>';
                    break;
                default:
                    $class=isset($action['class'])?$action['class']:'';
                    if (empty($action['controller'])){
                        $res .= '<a class="other-btn action-btn '.$class.'" href="#" data-pkey="'.$pkeyval.'">'.$action['label'].'</a>';
                    }else{
                        $res .= '<a class="other-btn action-btn '.$class.'" href="'.site_url($action['controller']).
                            $action['function'].'/'.$pkeyval.'">'.$action['label'].'</a>';
                    }
            }
        }
        return $res;
    }

    //分页总数
    public function getPageTotalNum($formtable,$where = array() )
    {
        $this->db->from($formtable);
        if (!empty($where)) $this->db->where($where);
        return $this->db->count_all_results();

    }

    public function getTable($formtype)
    {
        return $this->db->get_where(self::FORMTABLE,array('name'=>$formtype),1)->row_array();
    }

    public function getTableById($id)
    {
        return $this->db->get_where(self::FORMTABLE,array('id'=>$id),1)->row_array();
    }

    public function getMenus($priv)
    {
        $allmenus = $this->getAllMenus();
        switch ($priv)
        {
            case 27:
                $menus = array('menus'=>$allmenus);
                break;
            case 68:
                $menus = array('menus'=>array($allmenus[1],$allmenus[2]));
                break;
            default:
                $menus = '';
        }
        return $menus;
    }

    public function getAllMenus()
    {
        $all = array(
            array(
                'name'=>'系统管理',
                'list'=>array(
                    array('name'=>'系统表格','href'=>site_url('admin/form/showlist')),
                    array('name'=>'后台管理员','href'=>site_url('admin/adminuser/showlist')),
                    array('name'=>'用户权限组','href'=>site_url('admin/adminprivgroup/showlist')),
                    array('name'=>'用户权限','href'=>site_url('admin/adminpriv/showlist')),
                    array('name'=>'用户权限关系','href'=>site_url('admin/adminuserpriv/showlist')),
                    array('name'=>'微信登陆页面跳转','href'=>site_url('admin/redirect/showlist'))
                )
            ),
            array(
                'name'=>'用户管理',
                'list'=>array(
                    array('name'=>'用户列表','href'=>site_url('admin/user/showlist'))
                )
            ),
            array(
                'name'=>'问答社区',
                'list'=>array(
                    array('name'=>'概况','href'=>site_url('admin/adminmain')),
                    array('name'=>'系统通知','href'=>site_url('admin/commsysnotify/showlist')),
                    array('name'=>'首页轮播','href'=>site_url('admin/commbanner/showlist')),
                    array('name'=>'话题管理','href'=>site_url('admin/commsubject/showlist')),
                    array('name'=>'问题管理','href'=>site_url('admin/commquestion/showlist')),
                    array('name'=>'问题榜单','href'=>site_url('admin/commqrank/showlist')),
                    array('name'=>'问题授权','href'=>site_url('admin/commqpass/showlist'))
                )
            ),
            array(
                'name'=>'代言人',
                'list'=>array(
                    array('name'=>'代言人管理','href'=>site_url('admin/salesman/kdtsalesman/showList')),
                    array('name'=>'分享统计','href'=>site_url('admin/salesman/salesmanmanage/showList')),
//                    array('name'=>'渠道管理','href'=>site_url('admin/salesman/kdtsalesmantype/showList')),
                    array('name'=>'提现管理','href'=>site_url('admin/salesman/salesmanmoney/showList')),
                    array('name'=>'推文管理','href'=>site_url('admin/salesman/salesmanarticle/showList')),
//                    array('name'=>'海报管理','href'=>site_url('admin/salesman/salesmanpost/showList')),
                    array('name'=>'海报管理','href'=>site_url('admin/salesman/salesmanpostv2/showList')),
                    array('name'=>'海报分组管理','href'=>site_url('admin/salesman/salesmanposttype/showList')),
                    array('name'=>'海报路由管理','href'=>site_url('admin/salesman/salesmanpostroute/showList')),
                    array('name'=>'代言人邀请海报管理','href'=>site_url('admin/salesman/salesmaninvipost/showList')),
                    array('name'=>'商品管理','href'=>site_url('admin/salesman/salesmanproduct/showList')),
                )
            ),
            array(
                'name'=>'问卷管理',
                'list'=>array(
                    array('name'=>'问卷活动','href'=>site_url('admin/wenjuan/showList')),
                    array('name'=>'问卷组','href'=>site_url('admin/wenjuangroup/showList')),
                    array('name'=>'问卷问题','href'=>site_url('admin/wenjuanq/showList'))
                )
            ),
            array(
                'name'=>'课程投票',
                'list'=>array(
                    array('name'=>'课程管理','href'=>site_url('admin/xfmba/qfinfo/showList')),
                    array('name'=>'课程小组','href'=>site_url('admin/xfmba/qfgroup/showList')),
                )
            )
        );
        return $all;
    }

    public function create($formtable,$data)
    {
        return $this->insertData($formtable,$data);
    }

    public function createBuildForm($formtype)
    {
        $res = $this->getData(self::ITEMTABLE,'*',array('name'=>$formtype),0,0,'sort','ASC');
        $form = '<form action method="post" class="form-wrap" enctype="multipart/form-data"><ul>';
        foreach ($res as $row){
            $form .= $this->buildInput($row);
        }
        $form .= '</ul>';
        $form .= '<div class="submit-btn"><button type="submit">提交</button></div>';
        return $form;
    }

    public function update($formtable,$data,$pkey,$pkeyval)
    {
        $this->updateData($formtable,$data,array($pkey=>$pkeyval));
    }

    public function updateBuildForm($formtype,$formtable,$pkey,$pkeyval)
    {
        //获取原有数据
        $data = $this->getData($formtable,'*',array($pkey=>$pkeyval));
        $data = $data[0];
        //获取要编辑的项目
        $res = $this->getData(self::ITEMTABLE,'*',array('name'=>$formtype),0,0,'sort','ASC');
        $form = '<form action method="post" class="form-wrap" enctype="multipart/form-data"><ul>';
        foreach ($res as $row){
            $form .= $this->buildInput($row,$data);
        }
        $form .= '</ul>';
        $form .= '<div class="submit-btn"><button type="submit">提交</button></div>';
        return $form;
    }

    public function buildInput($row,$data='')
    {
        //该项目原有值
        $originval = empty($data[$row['ckey']])||!isset($data[$row['ckey']])? '':$data[$row['ckey']];

        $input = '<li class="'.$row['class'].'">';
        $input .= '<label>'.$row['cname'].'</label>';
        switch ($row['type']){
            case 'text':
                $input .= $this->load->view('admin/form/edit/text',array('ckey'=>$row['ckey'],
                    'request'=>$row['request'],'originval'=>$originval),true);
                break;
            case 'passwd':
                $input .= $this->load->view('admin/form/edit/passwd',array('ckey'=>$row['ckey'],
                    'request'=>$row['request']),true);
                break;
            case 'image':
                $originval = explode('|',$originval);
                foreach ($originval as &$v){
                    if (!empty($v)){
                        $v = preg_match("/http:\/\//i",$v)>0?$v:$this->_resource_url.$v;
                    }
                }
                $input .= $this->load->view('admin/form/edit/image',array('ckey'=>$row['ckey'],
                    'request'=>$row['request'],'originval'=>(empty($originval)?'':$originval)),true);
                break;
            case 'multiimage':
                $originval = explode('|',$originval);
                $count = 0;
                foreach ($originval as &$v){
                    if (!empty($v)){
                        $v = preg_match("/http:\/\//i",$v)>0?$v:$this->_resource_url.$v;
                        $count++;
                    }
                }
                $input .= $this->load->view('admin/form/edit/multiimage',array('ckey'=>$row['ckey'],'count'=>$count,
                    'request'=>$row['request'],'originval'=>(empty($originval)?'':$originval)),true);
                break;
            case 'audio':
                $originval = explode('|',$originval);
                $input .= $this->load->view('admin/form/edit/audio',array('ckey'=>$row['ckey'],
                    'request'=>$row['request'],'originval'=>$originval,'mediaurl'=>$this->_media_url),true);
                break;
            case 'select':
                //该项目选项
                $options = $row['value'];
                $options = explode('\n',$options);
                foreach ($options as &$v){
                    $v = explode('|',$v);
                }
                $input .= $this->load->view('admin/form/edit/select',array('ckey'=>$row['ckey'],
                    'options'=>$options,'originval'=>$originval),true);
                break;
            case 'dynamic_select':
                $func = explode('|',$row['func']);
                $param = preg_match('/\|/',$row['param'])?explode('|',$row['param']):array($row['param']);
                $this->load->model('admindynamic_model');
                $funcres = call_user_func_array('Admindynamic_model::'.$func[0],$param);
                $options = array();
                foreach ($funcres as $obj){
                    $options[] = array($obj[$func[1]],$obj[$func[2]]);
                }
                $input .= $this->load->view('admin/form/edit/select',array('ckey'=>$row['ckey'],
                    'options'=>$options,'originval'=>$originval),true);
                break;
            case 'textarea':
                $input .= $this->load->view('admin/form/edit/textarea',array('ckey'=>$row['ckey'],
                    'request'=>$row['request'],'originval'=>$originval),true);
                break;
            case 'editor':
                $input .= $this->load->view('admin/form/edit/editor',array('ckey'=>$row['ckey'],
                    'originval'=>$originval),true);
                break;
            case 'calender':
                $originval = empty($originval)?'':date('Y-m-d',$originval);
                $input .= $this->load->view('admin/form/edit/calender',array('ckey'=>$row['ckey'],
                    'request'=>$row['request'],'originval'=>$originval),true);
                break;
            case 'timestr':
                $originval = empty($originval)?'':date('Y-m-d H:i:s',$originval);
                $input .= $this->load->view('admin/form/edit/text',array('ckey'=>$row['ckey'],
                    'request'=>$row['request'],'originval'=>$originval),true);
                break;
            default:
                $input .= '';
        }
        $input .= '</li>';
        return $input;
    }

    public function getMultiAudio($id)
    {

    }
}